package com.cjjd.c.feature.mine.information;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cjjd.c.R;
import com.cjjd.c.ShareKeys;
import com.cjjd.c.base.ActionBarFragment;
import com.cjjd.c.bean.AddressInfoBean;
import com.cjjd.c.bean.AddressListBean;
import com.cjjd.c.bean.CityBean;
import com.cjjd.c.bean.HttpResult;
import com.cjjd.c.bean.ListResult;
import com.cjjd.c.bean.ProviceBean;
import com.cjjd.c.bean.RegionBean;
import com.cjjd.c.http.CallbackImpl;
import com.cjjd.c.http.JsonUtils;
import com.cjjd.c.utils.LogUtil;
import com.cjjd.c.utils.SharePrefUtil;
import com.cjjd.c.utils.StringUtil;
import com.cjjd.c.utils.ToastUtil;
import com.cjjd.c.view.WheelView_add;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;

import static com.cjjd.c.R.id.tv_address;

/**
 * ----------------------------------
 * Created by xyd on 2017/8/18.
 * <p/>
 * 描  述：
 * <p/>
 * 修订历史:
 * ----------------------------------
 */

public class AddressInforFragment extends ActionBarFragment {

    @Bind(R.id.et_name)
    EditText etName;
    @Bind(R.id.et_phone)
    EditText etPhone;
    @Bind(tv_address)
    TextView tvAddress;
    @Bind(R.id.ll_address)
    LinearLayout llAddress;
    @Bind(R.id.et_address_detail)
    EditText etAddressDetail;
    @Bind(R.id.et_postal_code)
    EditText etPostalCode;
    @Bind(R.id.tv_del)
    TextView tvDel;
    private String uuid;
    private AddressListBean addressInfoBean;


    @Override
    public Object getTitleString() {
        return "常用地址详情";
    }

    @Override
    public int getContentView() {
        return R.layout.fragment_address_info;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        initView();
        getProviceList();
        return rootView;
    }

    @Override
    protected void initView() {
        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        h1.put("uuid", uuid);

        Call<HttpResult<AddressInfoBean>> call = service.getCustomerAddressDetail(JsonUtils.convertParam("getCustomerAddressDetail", h1));
        call.enqueue(new CallbackImpl<AddressInfoBean>() {
            @Override
            public void responseSuccess(Call<HttpResult<AddressInfoBean>> call, Response<HttpResult<AddressInfoBean>> response) {
                addressInfoBean = response.body().getData().customerAddressModel;
                etName.setText(addressInfoBean.consignee);
                etPhone.setText(addressInfoBean.mobile);
                tvAddress.setText(addressInfoBean.area);
                etAddressDetail.setText(addressInfoBean.address);
                etPostalCode.setText(addressInfoBean.zipcode);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.tv_address,R.id.tv_del})
    public void onViewClicked(View view) {

        switch (view.getId()) {
            case R.id.tv_address:
                LogUtil.e("xyd", "获取省市区");
                if (proviceNameList.size() == 0 || cityNameList.size() == 0 || regionNameList.size() == 0) {
                    getProviceList();
                }

                LogUtil.e("xyd", "provice/city/region size is" + proviceNameList.size() + "/" + cityNameList.size() + "/" + regionNameList.size());
                if (proviceNameList.size() != 0 && cityNameList.size() != 0 && regionNameList.size() != 0) {
                    LogUtil.e("xyd", "provice/city/region size is" + proviceNameList.size() + "/" + cityNameList.size() + "/" + regionNameList.size());
                    showMutiChooseDateDialog(proviceNameList, cityNameList, regionNameList, "选择省市区");
                }

                break;
            case R.id.tv_del:

                deleAddress();
                break;
        }

    }

    @Override
    public void initRightButton(Button rightButton) {
        super.initRightButton(rightButton);
        rightButton.setText("保存");
        rightButton.setVisibility(View.VISIBLE);
        rightButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkCanUpdate()) {
                    updateAddress();
                }
            }
        });
    }

    private void updateAddress() {
        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        h1.put("uuid", addressInfoBean.uuid);               //
        h1.put("consignee", consignee);                     // 联系人/收件人
        h1.put("mobile", mobile);                           // 手机号
        h1.put("province", proviceCode);                     // 省编码
        h1.put("city", cityCode);                           // 市编码
        h1.put("region", regionCode);                       // 区编码
        h1.put("address", detailAddress);             // 详细地址
        h1.put("zipcode", zipcode);                         // 邮政编码

        Call<HttpResult<String>> call = service.addCustomerAddress(JsonUtils.convertParam("updateCustomerAddress", h1));
        call.enqueue(new CallbackImpl<String>() {
            @Override
            public void responseSuccess(Call<HttpResult<String>> call, Response<HttpResult<String>> response) {
                ToastUtil.showToast("更改成功");
                mContext.onBackPressed();
            }
        });
    }


    private boolean checkCanUpdate() {

        consignee = etName.getText().toString().trim();
        mobile = etPhone.getText().toString().trim();
        detailAddress = etAddressDetail.getText().toString().trim();
        zipcode = etPostalCode.getText().toString().trim();

        if (TextUtils.isEmpty(consignee)) {
            ToastUtil.showToast("请输入联系人姓名");
            return false;
        }

        if (!StringUtil.isMobile(mobile)) {
            ToastUtil.showToast("请输入正确的手机号");
            return false;
        }

        if (TextUtils.isEmpty(proviceCode)){
            ToastUtil.showToast("请选择所在地区");
        }

        if (TextUtils.isEmpty(detailAddress)) {
            ToastUtil.showToast("请输入详细地址");
            return false;
        }

        if (TextUtils.isEmpty(zipcode)) {
            ToastUtil.showToast("请输入邮政编码");
            return false;
        }
        return true;
    }

    private void deleAddress() {
        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        h1.put("uuids", uuid);

        Call<HttpResult<String>> call = service.delCustomerAddress(JsonUtils.convertParam("delCustomerAddress", h1));
        call.enqueue(new CallbackImpl<String>() {
            @Override
            public void responseSuccess(Call<HttpResult<String>> call, Response<HttpResult<String>> response) {
                ToastUtil.showToast("删除成功");
                mContext.onBackPressed();
            }
        });
    }

    public void setUuid(String uuid) {
        this.uuid = uuid;
    }



    private String consignee;
    private String mobile;
    private String provice;
    private String city;
    private String region;
    private String proviceCode;
    private String cityCode;
    private String regionCode;
    private String address;
    private String detailAddress;
    private String zipcode;

    private List<ProviceBean> proviceList = new ArrayList<ProviceBean>();
    private List<CityBean> cityList = new ArrayList<CityBean>();
    private List<RegionBean> regionList = new ArrayList<RegionBean>();

    private ArrayList<String> proviceNameList = new ArrayList<>();
    private ArrayList<String> proviceCodeList = new ArrayList<>();
    private ArrayList<String> cityNameList = new ArrayList<>();
    private ArrayList<String> cityCodeList = new ArrayList<>();
    private ArrayList<String> regionNameList = new ArrayList<>();
    private ArrayList<String> regionCodeList = new ArrayList<>();


    @Override
    protected void firstWheelviewChange(int id, String text, WheelView_add wheelView_second, WheelView_add wheelView_third) {
        super.firstWheelviewChange(id, text, wheelView_second, wheelView_third);
        LogUtil.e("xyd", "滑动到第几个: " + id);
        // 条目从 0 开始
        getCityList(proviceCodeList.get(id), wheelView_second, wheelView_third);
    }

    @Override
    protected void secondWheelviewChange(int id, String text, WheelView_add wheelView_third) {
        super.secondWheelviewChange(id, text, wheelView_third);
        getRegionList(cityCodeList.get(id), wheelView_third);
    }

    @Override
    protected void getMultiResult(int selected0, int selected1, int selected2, String title) {
        super.getMultiResult(selected0, selected1, selected2, title);
        LogUtil.e("xyd", "标题是：" + title + "三个选择分别是:" + selected0 + ";" + selected1 + ";" + selected2);
        if (selected0 >= 0) {
            proviceCode = proviceCodeList.get(selected0);
            provice = proviceNameList.get(selected0);
        } else {
            // TODO: 2017/9/28 特殊省市区需要处理
            proviceCode = "-1";
        }
        if (selected1 >= 0) {
            cityCode = cityCodeList.get(selected1);
            city = cityNameList.get(selected1);
        } else {
            cityCode = "-1";
        }
        if (selected2 >= 0) {
            regionCode = regionCodeList.get(selected2);
            region = regionNameList.get(selected2);
        } else {
            regionCode = "-1";
        }
        tvAddress.setText("" + provice + " " + city + " " + region);

    }


    private void getProviceList() {
        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));

        Call<HttpResult<ListResult<ProviceBean>>> call = service.getProvinceList(JsonUtils.convertParam("getProvinceList", h1));
        call.enqueue(new CallbackImpl<ListResult<ProviceBean>>() {
            @Override
            public void responseSuccess(Call<HttpResult<ListResult<ProviceBean>>> call, Response<HttpResult<ListResult<ProviceBean>>> response) {
                if (proviceList.size() > 0) {
                    proviceList.clear();
                }
                LogUtil.e("xyd", "provicelist is null ? " + (proviceList == null));
                LogUtil.e("xyd", "return provicelist is null ? " + (response.body().data.dataList == null));
                proviceList.addAll(response.body().data.dataList);

                if (proviceNameList.size() > 0) {
                    proviceNameList.clear();
                    proviceCodeList.clear();
                }
                for (ProviceBean proviceItem : proviceList) {
                    proviceCodeList.add(proviceItem.uuid);
                    proviceNameList.add(proviceItem.provinceName);
                }

                // 110000 北京市
                if (proviceList.size() > 0) {
                    getCityList(proviceList.get(0).uuid, null, null);
                }
            }
        });
    }

    private void getCityList(String provinceUuid, final WheelView_add wheelView_second, final WheelView_add wheelView_third) {
        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        h1.put("provinceUuid", provinceUuid);

        Call<HttpResult<ListResult<CityBean>>> call = service.getCityList(JsonUtils.convertParam("getCityList", h1));
        call.enqueue(new CallbackImpl<ListResult<CityBean>>() {
            @Override
            public void responseSuccess(Call<HttpResult<ListResult<CityBean>>> call, Response<HttpResult<ListResult<CityBean>>> response) {
                if (cityList.size() > 0) {
                    cityList.clear();
                }
                // 110100 市辖区
                cityList.addAll(response.body().data.dataList);

                if (cityNameList.size() > 0) {
                    cityNameList.clear();
                    cityCodeList.clear();
                }
                for (CityBean cityItem : cityList) {
                    cityCodeList.add(cityItem.uuid);
                    cityNameList.add(cityItem.cityName);
                }
                if (wheelView_second != null) {
                    wheelView_second.refreshData(cityNameList);
                }
                if (cityList.size() > 0) {
                    getRegionList(cityList.get(0).uuid, wheelView_third);
                } else {
                    regionNameList.clear();
                    regionCodeList.clear();
                    if (wheelView_third != null) wheelView_third.refreshData(regionNameList);
                }
            }
        });

    }


    private void getRegionList(String cityUuid, final WheelView_add wheelView_third) {
        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        h1.put("cityUuid", cityUuid);

        Call<HttpResult<ListResult<RegionBean>>> call = service.getRegionList(JsonUtils.convertParam("getRegionList", h1));
        call.enqueue(new CallbackImpl<ListResult<RegionBean>>() {
            @Override
            public void responseSuccess(Call<HttpResult<ListResult<RegionBean>>> call, Response<HttpResult<ListResult<RegionBean>>> response) {
                if (regionList.size() > 0) {
                    regionList.clear();
                }
                // 110101 东城区
                regionList.addAll(response.body().data.dataList);
                if (regionNameList.size() > 0) {
                    regionNameList.clear();
                    regionCodeList.clear();
                }
                for (RegionBean regionItem : regionList) {
                    regionCodeList.add(regionItem.uuid);
                    regionNameList.add(regionItem.regionName);
                }
                if (wheelView_third != null) {
                    wheelView_third.refreshData(regionNameList);
                }

            }
        });

    }
}
